<?php

namespace app\common\model\goods;

use think\Model;
use traits\model\SoftDelete;


class LihuaGoods extends Model
{

    // 表名
    protected $table = 'lihua_goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 启用软删除
    use SoftDelete;

    // 追加属性
    protected $append = [
        //'status_text',
    ];

    // 新增记录更新排序
    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    // 重设商品原始价格
    protected function setOriginalPriceAttr($value, $data)
    {
        return $value ?: null;
    }

    // 商品状态
    public function getStatusList()
    {
        return ['0' => '下架', '1' => '在售'];
    }

    // 关联城市模型
    public function lihuacity()
    {
        return $this->belongsTo('app\common\model\general\LihuaCity', 'city_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    // 关联分类模型
    public function lihuacategory()
    {
        return $this->belongsTo('app\common\model\goods\LihuaCategory', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    // 获取城市商品数据 分类ID索引
    public static function getCityGoodsIdxCategoryId($city_id = 0, $store_id = 0)
    {
        $goods = [];
        $list  = self::all(function ($query) use ($city_id) {
            $now = date('Y-m-d H:i:s');
            $query->where(['city_id' => $city_id, 'status' => 1])
                ->where("'{$now}' BETWEEN `sale_start` AND `sale_end`")
                ->field('id,category_id,name,short_name,description,pic,original_price,price,box_fee,limit_num,at_least,is_alone_sale,enable_stock')
                ->order('weigh', 'desc');
        });

        if ($list) {
            foreach ($list as $k => $v) {
                if (strpos($v['pic'], 'http') === false) {
                    $v['pic'] = config('site_url') . $v['pic'];
                }
                $v['original_price'] = $v['original_price'] ? round($v['original_price'], 2) : 0;
                $v['price']   = round($v['price'], 2);
                $v['box_fee'] = round($v['box_fee'], 2);
                $goods[$v['category_id']][] = $v;
            }
        }

        return $goods;
    }


    // 获取城市商品
    public static function getCityGoodsList($city_id = 0, $store_id = 0)
    {
        $list  = [];
        $goods = self::getCityGoodsIdxCategoryId($city_id, $store_id);
        $cids  = LihuaCategory::getCityCategoryIds($city_id);

        foreach ($cids as $k => $cid) {
            if (isset($goods[$cid])) $list = array_merge($list, $goods[$cid]);
        }

        return $list;
    }

    // 获取城市分类商品
    public static function getCityCategoryGoodsList($city_id = 0, $store_id = 0)
    {
        $goods = self::getCityGoodsIdxCategoryId($city_id, $store_id);
        $cates = LihuaCategory::getCityCategoryList($city_id);

        foreach ($cates as $k => $v) {
            if (isset($goods[$v['id']])) {
                $cates[$k]['goods'] = $goods[$v['id']];
            } else {
                unset($cates[$k]);
            }
        }

        return array_values($cates);
    }

    // 获取购物车商品，订单历史不可使用
    public static function getCartGoodsList($store_id, $goods_nums = [])
    {
        $list = $goods_ids = $_goods_nums = [];
        $goods_stocks = $lack_ids = $lack_names = [];
        $goods_amount = $packing_fee = $alone_sale = 0;

        if ($goods_nums) {
            $ids = array_keys($goods_nums);
            //商品列表
            $list = self::all(function ($query) use ($ids) {
                $now = date('Y-m-d H:i:s');
                $query->whereIn('id', $ids)->where('status', 1)
                    ->where("'{$now}' BETWEEN `sale_start` AND `sale_end`")
                    ->field('id,category_id,name,short_name,description,pic,price,box_fee,limit_num,at_least,is_alone_sale,enable_stock');
            });
            //库存信息
            $stockArr = LihuaStock::whereIn('goods_id', $ids)
                ->where('store_id', $store_id)->whereNotNull('num')->column('goods_id,num');

            foreach ($list as $k => $v) {
                if (strpos($v['pic'], 'http') === false) {
                    $list[$k]['pic'] = config('site_url') . $v['pic'];
                }

                $num = (int)$goods_nums[$v['id']];//购买数
                if ($num < $v['at_least']) $num = $v['at_least'];//起订数
                if ($v['limit_num'] > 0 && $num > $v['limit_num']) $num = $v['limit_num'];//限购数
                if ($v['is_alone_sale'] == 1) $alone_sale = 1;//1有可单卖商品

                $stock = null;//库存数
                if ($v['enable_stock'] == 1) {
                    $stock = isset($stockArr[$v['id']]) ? $stockArr[$v['id']] : null;
                    if (!is_null($stock)) {
                        $goods_stocks[$v['id']] = $stock;
                        if ($num > $stock) {
                            $lack_ids[]   = $v['id'];
                            $lack_names[] = $v['name'];
                        }
                    }
                }

                $price = round($v['price'] * $num, 2);
                $goods_amount += $price;
                $packing_fee  += round($v['box_fee'] * $num, 2);

                $list[$k]['price']      = round($v['price'], 2);
                $list[$k]['box_fee']    = round($v['box_fee'], 2);
                $list[$k]['num']        = $num;
                $list[$k]['num_price']  = $price;
                $_goods_nums[$v['id']]  = $num;
            }
        }

        return [
            'goods'            => $list, //商品列表
            'goods_nums'       => $_goods_nums,//商品数量组，键名为商品ID
            'goods_stocks'     => $goods_stocks ? : null,//商品库存组，键名为商品ID
            'goods_amount'     => $goods_amount,//商品总金额
            'packing_fee'      => $packing_fee,//总包装费
            'lack_goods'       => ['ids' => $lack_ids, 'names' => $lack_names],//库存不足商品
            'alone_sale'       => $alone_sale,//1有可单卖商品
        ];
    }


}
